package cn.nie.service.impl;


import cn.nie.entity.Document;
import cn.nie.service.SearchService;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("searchService")
public class SearchServiceImpl implements SearchService{

    @Autowired
    SolrServer solrServer;
    public List<Document> searchResult(String keyword) throws SolrServerException {

        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q","item_describe:"+keyword);

        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("item_describe");
        solrQuery.setHighlightSimplePre("<span style='color:red'>");
        solrQuery.setHighlightSimplePost("</span>");

        QueryResponse query = solrServer.query(solrQuery);

        SolrDocumentList results = query.getResults();

        long numFound = results.getNumFound();

        List<Document> documents = new ArrayList<Document>();

        Map<String, Map<String, List<String>>> highlighting = query.getHighlighting();
        for (SolrDocument doc:results) {

            Document document = new Document();
            String id =(String)doc.get("id");
            document.setId(Integer.valueOf(id));
            Map<String, List<String>> stringListMap = highlighting.get(id);
            List<String> content = stringListMap.get("item_describe");
            document.setContent(content.get(0));
            document.setTitle(String.valueOf(doc.get("item_title")));
            documents.add(document);
        }


        return documents;
    }

}
